/**
 * 多收行李认领
 */
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, DatePicker, Select, Button, InputNumber } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  overchargePkgClaim,
  getPkgAccidentDetail,
  batchUpdateImg
} from '../service';
import { Const } from '../../Const';

const FormItem = Form.Item;
const { Option } = Select;
// const { RangePicker } = DatePicker;

import PicUpload from '../../lessBaggageManagement/components/PicUpload';
import ShowPic from '../../lessBaggageManagement/components/ShowPic';

const BaggageClaim = props => {

  const { modalVisible, onCancel, form, onSubmit, accidentId, ownerType } = props;

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([]);

  const [detailInfo, setDetailInfo] = useState({});

  // 认领
  const { run: runoverchargePkgClaim } = useRequest(data => overchargePkgClaim(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '认领');
      onSubmit();
    }
  });

  // 事故单详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '事故单详情');
      let data = res || {};
      setDetailInfo(data.pkgAccidentDetailInfoVo || {});
      let imgArr = data.pkgImgList || [];
      handleOriginPicArr(imgArr);
      let goodFileListData = imgArr.filter(item => {
        return item.oneType === 1
      });

      let touristFileListData = imgArr.filter(item => {
        return item.oneType === 2
      });

      let paperFileListData = imgArr.filter(item => {
        return item.oneType === 3
      });

      let luggageFileListData = imgArr.filter(item => {
        return item.oneType === 4
      });

      handleLostItemPicture({
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData,
      });
    }
  });

  // 批量修改图片
  const { run: runBatchUpdateImg } = useRequest(data => batchUpdateImg(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '批量修改图片');
      handleLostItemPicManageVisible(false);
      handleLostItemPicVisible(false);
      runGetPkgAccidentDetail({
        accidentId: accidentId
      });
    }
  });

  useEffect(() => {
    if (modalVisible) {
      runGetPkgAccidentDetail({
        accidentId: accidentId
      });
    }
  }, [accidentId, modalVisible]);

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = accidentId;
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr]);
  }

  // 禁用今天之后的时间
  const disabledEndDate = useCallback((current) => {
    return current && current > moment().endOf('day');
  }, []);

  // 禁用今天之前的时间
  const disabledStartDate = useCallback((current) => {
    return current && current < moment().endOf('day');
  }, []);

  // 确定
  const okHandle = useCallback(() => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      console.log(fieldsValue, accidentId, 'fieldsValue');
      runoverchargePkgClaim({
        ...fieldsValue,
        accidentId
      });
    });
  }, [form, accidentId]);

  // 证件号 - 验证
  const idNoValidator = useCallback((rule, value, callback) => {
    let idType = form.getFieldValue('idType');
    if (value) {
      Const.idNoValidator(idType, value, callback);
    } else {
      callback();
    }
  }, [form]);

  return (
    <Modal
      destroyOnClose
      title="认领"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="领取状态">
          {form.getFieldDecorator('recipientStatus', {
            rules: [
              { required: true, message: '请选择领取状态' }
            ],
            initialValue: ''
          })(
            <Select style={{ width: '100%' }}>
              {Const.recipientStatusList.map(item => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="领取人">
          {form.getFieldDecorator('recipient', {
            rules: [
              { required: true, message: '请输入领取人' }
            ],
            initialValue: ''
          })(
            <Input placeholder="请输入" maxLength={50} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="联系方式">
          {form.getFieldDecorator('phone', {
            rules: [
              { required: true, message: '请输入联系方式' },
              { pattern: Const.phoneMobileReg, message: '请输入正确的格式'}
            ],
            initialValue: ''
          })(
            <Input placeholder="请输入" maxLength={11} />
          )}
        </FormItem>
        {form.getFieldValue('recipientStatus') === '2' && <FormItem {...Const.formLayout} label="费用">
          {form.getFieldDecorator('expressPrice', {
            rules: [
              { required: true, message: '请输入费用' },
              { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '最多小数点后2位的数字' },
            ],
            initialValue: ''
          })(
            <InputNumber
              min={0}
              max={Const.inputNumMax}
              step={0.01}
              style={{ width: '100%' }}
              placeholder="请输入" />
          )}
        </FormItem>}
        {form.getFieldValue('recipientStatus') !== '2' && <FormItem {...Const.formLayout} label="证件类型">
          {form.getFieldDecorator('idType', {
            rules: [],
            initialValue: ''
          })(
            <Select style={{ width: '100%' }}>
              {Const.idTypeListForSearch.map(item => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>}
      </div>
      {form.getFieldValue('recipientStatus') !== '2' && <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="证件号">
          {form.getFieldDecorator('idNo', {
            rules: [
              { validator: idNoValidator }
            ],
            initialValue: ''
          })(
            <Input placeholder="请输入" maxLength={18} />
          )}
        </FormItem>
        {form.getFieldValue('recipientStatus') === '1' && <FormItem {...Const.formLayout} label="待领时间">
          {form.getFieldDecorator('waitTime', {
            rules: [
              { required: true, message: '请选择待领时间' }
            ],
            initialValue: ''
          })(
            <DatePicker
              format={Const.format}
              disabledDate={disabledStartDate}
              placeholder="请选择日期"
              style={{ width: '100%' }} />
          )}
        </FormItem>}
      </div>}
      {form.getFieldValue('recipientStatus') === '2' && <>
        <div className={styles.formContent}>
          <FormItem {...Const.formLayout} label="快递公司">
            {form.getFieldDecorator('expressCompany', {
              rules: [
                { required: true, message: '请选择快递公司' }
              ],
              initialValue: ''
            })(
              <Select style={{ width: '100%' }}>
                {Const.expressCompanyList.map(item => (
                  <Option key={item}>{item}</Option>
                ))}
              </Select>
            )}
          </FormItem>
          <FormItem {...Const.formLayout} label="快递时间">
            {form.getFieldDecorator('expressDate', {
              rules: [
                { required: true, message: '请选择快递时间' }
              ],
              initialValue: ''
            })(
              <DatePicker
                format={Const.format}
                disabledDate={disabledEndDate}
                placeholder="请选择日期"
                style={{ width: '100%' }} />
            )}
          </FormItem>
        </div>
        <div className={styles.formContent}>
          <FormItem {...Const.formLayout} label="快递单号">
            {form.getFieldDecorator('expressOrderId', {
              rules: [
                { required: true, message: '请输入快递单号' }
              ],
              initialValue: ''
            })(
              <Input placeholder="请输入" maxLength={50} />
            )}
          </FormItem>
          <FormItem {...Const.formLayout} label="收件地址">
            {form.getFieldDecorator('recipientAddress', {
              rules: [
                { required: true, message: '请输入收件地址' }
              ],
              initialValue: ''
            })(
              <Input placeholder="请输入" maxLength={100} />
            )}
          </FormItem>
        </div>
        <div className={styles.formContent}>
          <Button type="primary" onClick={() => handleLostItemPicManageVisible(true)}>图片管理</Button>
        </div>
      </>}
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={10}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          const success = await handleDelImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={10}
        status={detailInfo.status}
      ></ShowPic>}
    </Modal>
  )
};

export default Form.create()(BaggageClaim);
